/**
 * 
 */
package jface.viewers;

import org.eclipse.jface.viewers.CellNavigationStrategy;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.TableColumn;

/**

 * 
 */
public class GeneralCellNavigationStrategy extends CellNavigationStrategy {
	private final TableViewer tableViewer;

	/**
	 * @param tableViewer
	 */
	public GeneralCellNavigationStrategy(TableViewer tableViewer) {
		super();
		this.tableViewer = tableViewer;
	}

	@Override
	public ViewerCell findSelectedCell(ColumnViewer viewer,
			ViewerCell currentSelectedCell, Event event) {
		ViewerCell cell = internalFindSelectedCell(viewer, currentSelectedCell,
				event);

		if (cell != null) {
			TableColumn t = tableViewer.getTable().getColumn(
					cell.getColumnIndex());
			tableViewer.getTable().showColumn(t);
		}

		return cell;
	}

	private ViewerCell internalFindSelectedCell(ColumnViewer viewer,
			ViewerCell currentSelectedCell, Event event) {
		switch (event.keyCode) {
		case SWT.ARROW_UP:
			if (currentSelectedCell != null) {
				return CellUtils.getNeighbor(currentSelectedCell,
						ViewerCell.ABOVE, false);
			}
			break;
		case SWT.ARROW_DOWN:
			if (currentSelectedCell != null) {
				return CellUtils.getNeighbor(currentSelectedCell,
						ViewerCell.BELOW, false);
			}
			break;
		case SWT.ARROW_LEFT:
			if (currentSelectedCell != null) {
				return CellUtils.getNeighbor(currentSelectedCell,
						ViewerCell.LEFT, true);
			}
			break;
		case SWT.ARROW_RIGHT:
			if (currentSelectedCell != null) {
				return CellUtils.getNeighbor(currentSelectedCell,
						ViewerCell.RIGHT, true);
			}
			break;
		}

		return null;
	}

}
